import { createRouter, createWebHistory } from 'vue-router';
import Login from '@/components/Login.vue';
import Home from '@/components/Home.vue';
import ProductList from '@/components/ProductList.vue';
import Cart from '@/components/Cart.vue';
import Checkout from '@/components/Checkout.vue';
import store from '@/stores';

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/home',
      name: 'home',
      component: Home,
      meta: { requiresAuth: true }
    },
    {
      path: '/products',
      name: 'productList',
      component: ProductList,
      meta: { requiresAuth: true }
    },
    {
      path: '/cart',
      name: 'cart',
      component: Cart,
      meta: { requiresAuth: true }
    },
    {
      path: '/checkout',
      name: 'checkout',
      component: Checkout,
      meta: { requiresAuth: true }
    }
  ]
});

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth &&!store.state.isLoggedIn) {
    next('/login');
  } else {
    next();
  }
});

export default router;